﻿/*
 * ========================================================================
 * Copyright(c) 2007-2012 情留メ蚊子, All Rights Reserved.
 * Welcom use the LiteFetion.
 * See more information,Please goto http://www.94qing.com
 * ========================================================================
 * 
 * 作 者：情留メ蚊子
 * Q  Q: 540644769
 * 邮 箱：qlwz@qq.com
 * 网 址：http://www.94qing.com
 * ========================================================================
*/
using System;
using System.Net;
using LiteFetion.Model;
using LiteFetion.Utils;
using Newtonsoft.Json.Linq;

namespace LiteFetion
{
    /// <summary>
    /// 登录管理
    /// </summary>
    public class LoginManager
    {
        public LoginManager(FetionClient client)
        {
            FetionClient = client;
        }

        /// <summary>
        /// FetionClient
        /// </summary>
        public FetionClient FetionClient { get; private set; }

        /// <summary>
        /// User
        /// </summary>
        public User User { get { return FetionClient.User; } }


        /// <summary>
        /// 登录入口登录,完成主页面登录请求
        /// </summary>
        /// <param name="account">用户名，可以是手机号，飞信号，注册的邮件</param>
        /// <param name="password">密码</param>
        /// <param name="state">登录状态</param>
        /// <param name="verifyImage">验证码，登录的过程需要验证码</param>
        /// <returns></returns>
        public ActionResult Login(string account, string password, BuddyState state, VerifyImage verifyImage)
        {
            if (state != BuddyState.ONLINE && state != BuddyState.BUSY && state != BuddyState.AWAY && state != BuddyState.OFFLINE)
            {
                state = BuddyState.ONLINE;
            }
            string postData = string.Format("UserName={0}&Pwd={1}{2}&OnlineStatus={3}", account, password, verifyImage.VerifyCode.IsEmpty() ? "" : "&Ccp=" + verifyImage.VerifyCode, (int)state);
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_LOGIN;
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            if (verifyImage != null)
            {
                http.Cookies.Add(new Cookie(verifyImage.VerifyType, verifyImage.SessionId));
            }
            http.Do();

            http.Cookies.RemoveAll(p => p.Name.Compare(VerifyImage.TYPE_LOGIN));

            FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }
            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            switch (status)
            {
                case 200:
                    this.User.Cookies = http.Cookies;
                    Cookie cookie = User.Cookies.Find(p => p.Name.Compare("webim_sessionid"));
                    if (cookie != null)
                    {
                        this.User.SessionId = cookie.Value;
                        this.User.Cookies.Remove(cookie);
                    }
                    return ActionResult.SUCCESS;
                case 312:
                    return ActionResult.VERIFY_FAILED;
                case 404:
                    return ActionResult.USER_NOT_FOUND;
                case 321:
                    return ActionResult.PASSWORD_NOT_MATCH;
                default:
                    return ActionResult.REQUEST_FAILED;
            }
        }

        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPersonalInfo()
        {
            string postData = string.Format("ssid={0}", this.User.SessionId);
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_GET_PERSONAL_INFO.FormatWith(this.FetionClient.RequestVersion++);
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            http.Do();

            FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }

            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            if (status != 200)
            {
                return ActionResult.HTTP_FAILED;
            }
            json = json.Value<JObject>("rv");

            User.Mobile = json.Value<string>("mn");
            User.NickName = json.Value<string>("nn");
            User.Uri = json.Value<string>("uri");
            if (json["sid"] != null)
            {
                User.Sid = json.Value<int>("sid");
            }
            User.UserId = json.Value<int>("uid");
            User.Impresa = json.Value<string>("i");
            return ActionResult.SUCCESS;
        }

        /// <summary>
        /// 获取好友的列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetBuddyList()
        {
            string postData = string.Format("ssid={0}", this.User.SessionId);
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_GET_CONTACT_LIST.FormatWith(this.FetionClient.RequestVersion++);
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            http.Do();

            FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }
            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            if (status != 200)
            {
                return ActionResult.HTTP_FAILED;
            }

            json = json.Value<JObject>("rv");

            JArray jArrays = json.Value<JArray>("bds");
            if (jArrays == null)
            {
                jArrays = new JArray();
            }
            JObject temp = null;
            Buddy buddy = null;
            for (int j = 0; j < jArrays.Count; j++)
            {
                temp = Util.GetObjectResult(jArrays[j].ToString());
                buddy = new Buddy();
                buddy.Uri = temp.Value<string>("uri");
                buddy.UserId = temp.Value<int>("uid");
                buddy.IsBlack = (temp.Value<int>("isBk") == 1);
                buddy.LocalName = temp.Value<string>("ln");
                buddy.CordIds = temp.Value<string>("bl");
                buddy.Relation = Buddy.GetRelation(temp.Value<int>("rs"));
                FetionClient.BuddyList.Add(buddy);
            }

            jArrays = json.Value<JArray>("bl");
            if (jArrays == null)
            {
                jArrays = new JArray();
            }
            Cord cord = null;
            for (int j = 0; j < jArrays.Count; j++)
            {
                temp = Util.GetObjectResult(jArrays[j].ToString());
                cord = new Cord();
                cord.Id = temp.Value<int>("id");
                cord.Name = temp.Value<string>("n");
                FetionClient.CordList.Add(cord);
            }
            return ActionResult.SUCCESS;
        }

        /// <summary>
        /// 退出登录，完成主页面退出请求
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            string postData = string.Format("ssid={0}", this.User.SessionId);
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_LOGOUT.FormatWith(this.FetionClient.RequestVersion++);
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            http.Do();

            FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }
            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            if (status != 200)
            {
                return ActionResult.HTTP_FAILED;
            }
            return ActionResult.SUCCESS;
        }
    }
}
